<template>
  <view class="footprint-container">
    <!-- 顶部头像与文字，覆盖在地图之上 -->
    <view class="map-header">
      <view class="profile">
        <image class="avatar" :src="avatarSrcComputed" mode="aspectFill" />
        <view class="profile-text">
          <text class="name">{{ displayName }}</text>
          <view class="stats">
            <text class="stat-line">你已在半边集留下 <text class="num">{{ footprintsCount }}</text> 个足迹</text>
            <text class="stat-line">遍布 <text class="num">{{ cityCount }}</text> 个城市， <text class="num">{{ footprintsCount }}</text> 个地点</text>
          </view>
        </view>
      </view>
    </view>

    <map 
      v-if="canUseMap" 
      class="map" 
      id="fp-map"
      :latitude="center.lat" 
      :longitude="center.lng" 
      :markers="markers" 
      :polyline="polyline"
      :include-points="includePoints"
    />
    <view v-else class="fallback">
      <view class="pin" v-for="(c, i) in cities" :key="i" :style="pinStyle(i)">
        <view class="pin-dot"></view>
        <text class="pin-label">{{ c.name }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref,  watch,  computed } from 'vue';
import { getStorage, setStorage } from '../../utils/storage';
import defaultImg from '../../static/头像/image.png'

//遍历活动地点列表，提取城市名称数组传入cities变量
const activityLoc = ref([
  '广州市黄浦区XXX路XXX号',
  '北京市朝阳区XXX路XXX号',
  '上海市浦东新区XXX路XXX号'
])
const cities =computed(()=>{
  const citySet = new Set<string>();
  activityLoc.value.forEach(loc => {
    const cityMatch = loc.match(/^(.*?市|.*?区|.*?县)/);
    if (cityMatch) {
      citySet.add(cityMatch[1]);
    }
  });
  return Array.from(citySet).map(name => ({ name }));
})

const qqMapKey = 'F43BZ-S3LK5-D2SI4-IXXVE-3NH3E-3CFI7';
const userInfo = ref({
  name: 'Janice',
  avatar: ''//url或者base64
})

const GEO_CACHE_KEY = 'FOOTPRINT_GEO_CACHE';
// 常用城市离线经纬度（简版，可按需扩展）
const CITY_COORDS: Record<string, { lat: number; lng: number }> = {
  '北京': { lat: 39.9042, lng: 116.4074 },
  '北京市': { lat: 39.9042, lng: 116.4074 },
  '上海': { lat: 31.2304, lng: 121.4737 },
  '上海市': { lat: 31.2304, lng: 121.4737 },
  '广州': { lat: 23.1291, lng: 113.2644 },
  '广州市': { lat: 23.1291, lng: 113.2644 },
  '深圳': { lat: 22.5431, lng: 114.0579 },
  '深圳市': { lat: 22.5431, lng: 114.0579 },
  '杭州': { lat: 30.2741, lng: 120.1551 },
  '杭州市': { lat: 30.2741, lng: 120.1551 },
  '成都': { lat: 30.5728, lng: 104.0668 },
  '成都市': { lat: 30.5728, lng: 104.0668 },
};

const center = ref({ lat: 23.1291, lng: 113.2644 })//初始以广州为中心
const markers = ref<any[]>([]);
const polyline = ref<any[]>([]);
const canUseMap = ref(false);
const cityCache = ref<Record<string, { lat: number; lng: number }>>(getStorage(GEO_CACHE_KEY) || {});

async function geocode(city: string): Promise<{ lat: number; lng: number } | null> {
  if (cityCache.value[city]) return cityCache.value[city];
  if (CITY_COORDS[city]) return CITY_COORDS[city];
  if (!qqMapKey) return null;
  try {
    const url = `https://apis.map.qq.com/ws/geocoder/v1/?address=${encodeURIComponent(city)}&key=${qqMapKey}`;
    const res: any = await new Promise((resolve, reject) => {
      uni.request({ url, success: resolve, fail: reject });
    });
    const loc = res?.data?.result?.location;
    if (loc && typeof loc.lat === 'number' && typeof loc.lng === 'number') {
      cityCache.value[city] = { lat: loc.lat, lng: loc.lng };
      setStorage(GEO_CACHE_KEY, cityCache.value);
      return cityCache.value[city];
    }
  } catch (e) {
    console.warn('Geocode failed:', city, e);
  }
  return null;
}

async function buildMap() {
  const points: { lat: number; lng: number; name: string }[] = [];
  for (const c of cities.value) {
    const loc = await geocode(c.name);
    if (loc) points.push({ ...loc, name: c.name });
  }
  if (points.length > 0) {
    // 先设置 canUseMap，让地图组件渲染
    canUseMap.value = true;
    markers.value = points.map((p, i) => ({
      id: i,
      latitude: p.lat,
      longitude: p.lng,
      width: 28,
      height: 28,
      iconPath: '/static/我的足迹/u587.svg',
      callout: { content: p.name, display: 'ALWAYS', color: '#fff', bgColor: '#314039', borderRadius: 6, padding: 6 }
    }));
    center.value = { lat: points[0].lat, lng: points[0].lng };
    polyline.value = [{ points: points.map(p => ({ latitude: p.lat, longitude: p.lng })), color: '#a8c6df', width: 3, dottedLine: true }];
  } else {
    // 没有点位也显示地图，便于排查 key/域名问题
    canUseMap.value = true;
    markers.value = [];
    center.value = { lat: 31.2304, lng: 121.4737 };
    polyline.value = [];
  }
}

const includePoints = computed(()=>markers.value.map(m => ({ 
  latitude: m.latitude, 
  longitude: m.longitude 
})))

// 顶部展示使用的计算字段
const displayName = computed(()=> userInfo.value.name || '访客');
const avatarSrcComputed = computed(()=> userInfo.value.avatar || defaultImg);
const footprintsCount = computed(()=> activityLoc.value.length);
const cityCount = computed(()=> {
  // 优先使用 markers 长度（已解析到经纬的点），否则回落为 cities 中的 count 汇总或 cities 数量
  if (markers.value && markers.value.length > 0) return markers.value.length;
  return cities.value.length || 0
});

function pinStyle(idx: number) {
  // 简单散点布局，避免重叠（非地图兜底）
  const cols = 3;
  const row = Math.floor(idx / cols);
  const col = idx % cols;
  const top = 40 + row * 140;
  const left = 10 + col * 30 + (row % 2 === 0 ? 10 : 0);
  return `top:${top}rpx; left:${left}rpx;`;
}

watch(() => cities, () => { 
  buildMap(); 
}, {  immediate: true,deep: true });
</script>

<style lang="scss">
.footprint-container { 
  width: 100%; height: 100vh; position: relative;
  /* 顶部覆盖信息 */
  .map-header {
    position: absolute;
    top: 20rpx;
    left: 20rpx;
    right: 20rpx;
    z-index: 110;
    pointer-events: none; /* 不阻塞地图交互 */
    .profile {
      display: flex;
      align-items: center;
      gap: 20rpx;
      background: rgba(49,64,57,0.12);
      padding: 20rpx;
      border-radius: 12rpx;
      backdrop-filter: blur(2rpx);
    }
  .avatar { width: 88rpx; height: 88rpx; border-radius: 50%; border: 4rpx solid rgba(255,255,255,0.12); }
  .profile-text { pointer-events: auto; }
  .name { display: block; color: #314039; font-size: 40rpx; font-weight: 700; }
  .stats { margin-top: 8rpx; }
  .stat-line { display: block; color: #314039; opacity: 0.9; font-size: 24rpx; margin-top: 6rpx; }
  .num { color: #000; font-weight: 700; font-size: 28rpx; }
  }

  // 地图
  .map { width: 100%; height: 100%; }
  .fallback { position: relative; width: 100%; height: 100%; }
  .pin { position: absolute; }
  .pin-dot { width: 24rpx; height: 24rpx; border-radius: 50%; background: #d7d7d7; border: 4rpx solid #000; }
  .pin-label { display: block; margin-top: 8rpx; color: #fff; font-size: 24rpx; }
}
</style>